//
//  HRVModel.swift
//  DaFit
//
//  Created by 尹琼 on 2022/6/11.
//  Copyright © 2022 sylar. All rights reserved.
//

import UIKit
import SQLite
import SwiftDate
import HandyJSON
import MYModule


open class SingleHRVModel: NSObject, MYSQLiteTableiabe, SingleSQLite, HandyJSON {
    
    public var adress: String = ""
    
    public var id: Int64 = 0
    
    public var date: Date = Date().sqlDate()
    
    ///  hrv 值 单位： 毫秒
    public var hrv: Int = 0
    
 
    /// 结束测量时间戳
    public var end: Double = 0
    
    /// hrv 单位
    public let hrv_unit = "ms"
    
    
    required public override init() {}
    
    
    @discardableResult
    public func updateData() ->Bool {
        
        if hrv <= 0 || hrv >= 1500 {
            return false
        }
        if end <= 0 {
            return false
        }
    
        if id == 0 {
            insert()
            return true
        }
        
        update()
        return true
        
    }
    
    
    /// 一天的HRV测量（每半小时一个数组）
    /// - Parameter date: 日期
    /// - Returns: [[]]
    public static func halfAnHourForDay(from date: Date) ->[[SingleHRVModel]] {
        
        let models = SingleHRVModel.day(from: date)
        
        let time = Date(year: date.year, month: date.month, day: date.day, hour: 0, minute: 0).timeIntervalSince1970
        
        var minutesModels = (0 ..< 1440).map { _ in SingleHRVModel() }
        
        models.forEach {
            let minute = Int(($0.end - time)/60)
            minutesModels[minute] = $0
        }
        
        var array: [[SingleHRVModel]] = []
        var subArray: [SingleHRVModel] = []
        
        
        minutesModels.forEach {
            
            subArray.append($0)
            
            // 每 30个放一个数组
            if !subArray.isEmpty && subArray.count%30 == 0 {
                
                let sub = subArray.filter { model ->Bool in
                    return model.hrv > 0
                    
                }
                array.append(Array(sub))
                subArray.removeAll()
                
            }
            
        }
        
        if subArray.isEmpty {
            let sub = subArray.filter { model ->Bool in
                return model.hrv > 0
                
            }
            array.append(Array(sub))
            subArray.removeAll()
        }
        
        return array
        
    }


}
